from datetime import datetime
import json
from sqlalchemy import select
from pathlib import Path
from databases.sync import get_db
from table.model.v1 import CodeBatchModel


class SyncDataService:
    def __init__(self):
        self.db = get_db()

    def get_file_path(self, name: str):
        root_path = Path(__file__).parent.parent
        save_file = root_path / "static"
        save_file.mkdir(parents=True, exist_ok=True)
        return save_file / f"{name}.json"

    def save(self, file_path: Path, data: list[dict]):
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(data, ensure_ascii=False))

    def test_db_connect(self):
        """测试数据库连接"""
        statment = select(CodeBatchModel)
        result = self.db.execute(statment).scalars().all()
        for row in result:
            print(row.id)

    def load_old_data(self, model):
        """加载旧数据"""
        result = self.db.execute(select(model)).scalars().all()
        data = []
        for row in result:
            row_dict = {}
            for key in row.__table__.columns.keys():
                row_dict[key] = getattr(row, key)
                if isinstance(row_dict[key], datetime):
                    row_dict[key] = row_dict[key].isoformat()

            data.append(row_dict)
        name = model.__tablename__
        # print("name",name)
        # print("tablename",model.__tablename__)
        # print("table",model.__table__)
        file_path = self.get_file_path(name)
        print("file_path", file_path)
        self.save(file_path, data)

    def upload_new_data(self):
        """上传新数据"""
        pass



